package com.coupon.controller;

import com.common.constant.CouponStatus;
import com.common.domain.dto.CouponAddDTO;
import com.common.domain.dto.CouponIssueFormDTO;
import com.common.domain.dto.CouponListByConditionDTO;
import com.common.domain.dto.CouponUpdateDTO;
import com.common.domain.po.Coupon;
import com.common.domain.vo.CouponLIstByConditionVO;
import com.common.exception.CodeAndMsg;
import com.common.exception.JavaSmException;
import com.common.result.Result;
import com.coupon.service.CouponService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * @author 路亚
 * @version 0.1
 * @className CouponController
 * @description
 * @date 2024/12/21 15:05
 * @since jdk11
 */
@RestController
@RequestMapping("/coupon")
@Slf4j
@Api(tags = "优惠券管理")
@RequiredArgsConstructor
public class CouponController {

    private final CouponService couponService;

    @PostMapping("/add")
    @ApiOperation("添加优惠券")
    public Result add(@RequestBody CouponAddDTO couponAddDTO){
        log.info("添加优惠券,添加数据为:{}", couponAddDTO);
        couponService.add(couponAddDTO);
        return Result.success();
    }

    @PostMapping("/update")
    @ApiOperation("修改优惠券")
    public Result update(@RequestBody CouponUpdateDTO couponUpdateDTO){
        log.info("修改优惠券,修改数据为:{}", couponUpdateDTO);
        couponService.updateCouponById(couponUpdateDTO);
        return Result.success();
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除优惠券")
    public Result delete(Long id){
        log.info("删除优惠券,id为:{}", id);
        Coupon coupon = couponService.getById(id);
        if (coupon == null){
            throw new JavaSmException(CodeAndMsg.COUPON_NOT_EXIST);
        }
        if (coupon.getStatus() != CouponStatus.TO_BE_ISSUED){
            throw new JavaSmException(CodeAndMsg.COUPON_STATUS_ERROR);
        }
        couponService.removeById(id);
        return Result.success();
    }

    @GetMapping("/listByCondition")
    @ApiOperation("优惠券列表分页查询")
    public Result listByCondition(CouponListByConditionDTO couponListByConditionDTO, Integer page){
        log.info("优惠券列表分页查询,查询条件为:{}", couponListByConditionDTO);
        CouponLIstByConditionVO result = couponService.listByCondition(couponListByConditionDTO, page);
        return new Result(200, "OK", result);
    }

    @PostMapping("/issueCoupon")
    @ApiOperation("发放优惠券")
    public Result issueCoupon(@RequestBody CouponIssueFormDTO couponIssueFormDTO){
        couponService.issueCoupon(couponIssueFormDTO);
        return Result.success();
    }
}
